<template>
  <div class="wh-100 card cbox" style="background-color: white">
    <div class="d-flex-between-center  pl-24 ch50">
      <div class="fs-14 fw-6">预警统计</div>
    </div>
    <div class="h-7   d-flex-align-center pl-24">
      <Select v-if="userInfo.resource == 1" class="w-10 ml-8" v-model="searchForm.schoolCode" clearable filterable @on-change="selectSchool"
              placeholder="所有高校">
        <Option v-for="item in schoolList" :value="item.schoolCode" :key="item.schoolCode">{{ item.schoolName }}</Option>
      </Select>
      <Select v-if="userInfo.resource == 1 || userInfo.resource == 2" class="w-15 ml-8" v-model="searchForm.college" @on-change="selectCollege"
              filterable clearable placeholder="所有院系">
        <Option v-for="item in collegeList" :value="item" :key="item">{{ item }}</Option>
      </Select>
      <Select v-if="userInfo.resource == 1 || userInfo.resource == 2 || userInfo.resource == 3" class="w-15 ml-8" v-model="searchForm.profession"
              filterable clearable placeholder="专业">
        <Option v-for="item in zyList" :value="item" :key="item">{{ item }}</Option>
      </Select>
      <Button type="primary" @click="getRecordPage">查询</Button>
      <div class="ml-auto mr-12">
        <Button type="primary" @click="exportAllData">导出全部数据</Button>
      </div>
    </div>
    <div class="h-80 w-100 ctable">
      <TableV2
          id="table1"
          class="wh-100"
          show-summary
          :summary-method="handleSum"
          border
          :columns="tableColumns"
          :data="tableData"
          ref="table1"
          :height="refHeight.value"
      ></TableV2>
    </div>
  </div>
</template>

<script>
import TableV2 from '@/views/xboot-components/table/table-v2.vue';

import { getAllCollege, proGetAllCollage } from '../../api/bys/yx/yx';

import { accessToAllNonProvincialSchoolsApi, getCollegesApi, getSchoolsApi, getZysApi } from '../../api/bys/gxjyl/jyqx';
import { getStatisticsDataApi } from '../../api/dataVerification/dataVerification';
import { saveAs } from 'file-saver';
import XLSX from 'xlsx';
import cloneDeep from 'lodash/cloneDeep';

export default {
  components: { TableV2 },

  data() {
    return {
      refHeight: { value: 0 },
      tableColumns: [],
      tableColumns_1: [

        {
          title: '专业',
          key: 'profession',
          minWidth: 200,
          align: 'center',
          sortable: true
        },

        {
          title: '总计',
          key: 'total',
          width: 100,
          align: 'center'
        },
        {
          title: '材料核查',
          key: '',
          minWidth: 100,
          align: 'center',
          sortable: false,
          children: [
            {
              title: '材料完整且与毕业去向一致',
              key: 'materialComplete',
              minWidth: 220,
              sortable: true,
              disability: false
            },
            {
              title: '材料不完整',
              key: 'materialNoComplete',
              minWidth: 130,
              sortable: true
            },
            {
              title: '材料与毕业去向不一致',
              key: 'materialInconsistent',
              minWidth: 200,
              sortable: true
            }
          ]
        },
        {
          title: '学生电话核查',
          key: '',
          minWidth: 100,
          align: 'center',
          sortable: false,
          children: [
            {
              title: '毕业去向信息无误',
              key: 'studentComplete',
              minWidth: 170,
              sortable: true,
              disability: false
            },
            {
              title: '毕业去向信息有误，曾经在此单位工作，目前未就业',
              key: 'studentInNotEmployed',
              minWidth: 380,
              sortable: true
            },
            {
              title: '毕业去向信息有误，曾经在此单位工作，目前已换工作单位',
              key: 'studentInChangedEmployer',
              minWidth: 380,
              sortable: true
            },
            {
              title: '毕业去向信息有误，学生从未登记该毕业去向信息或该毕业去向信息与学生无关，目前已就业',
              key: 'studentNeverIsEmployed',
              minWidth: 380,
              sortable: true,
              disability: false
            },
            {
              title: '毕业去向信息有误，学生从未登记该毕业去向信息或该毕业去向信息与学生无关，目前未就业',
              key: 'studentNeverNotEmployed',
              minWidth: 380,
              sortable: true
            }
          ]
        },
        {
          title: '用人单位电话核查',
          key: '',
          minWidth: 100,
          align: 'center',
          sortable: false,
          children: [
            {
              title: '毕业去向信息无误',
              key: 'enterpriseComplete',
              minWidth: 170,
              sortable: true,
              disability: false
            },
            {
              title: '学生与该单位签约过，但已解约或未入职',
              key: 'enterpriseTerminated',
              minWidth: 230,
              sortable: true
            },
            {
              title: '学生在该单位工作过，但已离职',
              key: 'enterpriseLeft',
              minWidth: 200,
              sortable: true
            },
            {
              title: '该单位仅为学生的实习单位',
              key: 'enterpriseInternship',
              minWidth: 200,
              sortable: true,
              disability: false
            },
            {
              title: '该单位与学生没有任何关系',
              key: 'enterpriseNotMatter',
              minWidth: 180,
              sortable: true
            }
          ]
        }
      ],
      tableData: [],
      schoolList: [],
      zyList: [],
      collegeList: [],
      searchForm: {
        schoolCode: '',
        schoolName: '',
        college: '',
        profession: ''
      },
      userInfo: JSON.parse(Cookies.get('userInfo'))
    };
  },
  methods: {
    selectSchool(val) {
      console.log(val,'选中值');
      this.getCollegeList();
      this.getZyList();
    },
    selectCollege(val) {
      console.log(val,'选中值');
      this.getZyList();
    },
    exportAllData() {
      let elementId = 'table1';
      let excelName = '预警统计数据.xlsx';
      // 通过table的id获取表格元素
      const table = document.getElementById(elementId);
      const ws = XLSX.utils.table_to_sheet(table, { raw: true });

      // 设置所有列为字符串格式
      const range = XLSX.utils.decode_range(ws['!ref']);
      for (let column = range.s.c; column <= range.e.c; column++) {
        for (let row = range.s.r; row <= range.e.r; row++) {
          const cellRef = XLSX.utils.encode_cell({ c: column, r: row });
          if (!ws[cellRef]) continue;
          ws[cellRef].z = 's';
        }
      }


      // 确定最后一行的行号
      const lastRowNum = range.e.r;
      // 遍历最后一行的每个单元格并删除它们(最后一行为多余数据，暂无筛选结果)
      for (let colIndex = range.s.c; colIndex <= range.e.c; colIndex++) {
        const cellAddress = XLSX.utils.encode_cell({ c: colIndex, r: lastRowNum });
        if (ws[cellAddress]) {
          delete ws[cellAddress]; // 删除单元格
        }
      }


      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
      const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });

      function s2ab(s) {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
        return buf;
      }

      saveAs(new Blob([s2ab(wbout)], { type: 'application/octet-stream' }), excelName);
    },
    getRecordPage() {
      getStatisticsDataApi(this.searchForm).then(res => {
        this.tableData = res.result;
        console.log('预警统计数据', res);
      });
    },
    handleSum({ columns, data }) {
      let userInfo = JSON.parse(Cookies.get('userInfo'));
      const sums = {};
      columns.forEach((column, index) => {
        const key = column.key;
        if (index === 0) {
          sums[key] = {
            key,
            value: '总计'
          };
          return;
        }
        if (index === 1 && (userInfo.resource == 1 || userInfo.resource == 2)) {
          sums[key] = {
            key,
            value: ''
          };
          return;
        }
        if (index === 2 && (userInfo.resource == 1)) {
          sums[key] = {
            key,
            value: ''
          };
          return;
        }
        const values = data.map(item => Number(item[key]));
        if (!values.every(value => isNaN(value))) {
          const v = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[key] = {
            key,
            value: v
          };
        } else {
          sums[key] = {
            key,
            value: ''
          };
        }
      });
      return sums;
    },
    getSchoolList() {
      // 学校
      getSchoolsApi().then(res => {
        if (res.success) {
          this.schoolList = res.result;
        }
      });
    },
    getCollegeList() {
      getCollegesApi({
        schoolCode: this.searchForm.schoolCode,
      }).then(res => {
        if (res.success) {
          this.collegeList = res.result;
        }
      })
    },
    getZyList() {
      getZysApi({
        schoolCode: this.searchForm.schoolCode,
        college: this.searchForm.college,
      }).then(res => {
        if (res.success) {
          this.zyList = res.result;
        }
      })
    },
    onRestWindow() {
      let t1 = cloneDeep(this.tableColumns_1);
      this.restTreeTableCellWidth(t1);
      this.tableColumns = t1;
    }

  },
  mounted() {
    this.onRestWindow();
    window.addEventListener('resize', this.onRestWindow);
    let userInfo = JSON.parse(Cookies.get('userInfo'));
    if (userInfo.resource == 1) {
      let arr1 = [
        {
          title: '高校名称',
          key: 'schoolName',
          minWidth: 200,
          align: 'center',
          sortable: true
        },
        {
          title: '院系名称',
          key: 'college',
          minWidth: 200,
          align: 'center',
          sortable: true
        }
      ];
      let arr01 = this.restTableCellWidth(arr1);
      this.tableColumns = arr01.concat(this.tableColumns);

    }
    if (userInfo.resource == 2) {
      let arr1 = [
        {
          title: '院系名称',
          key: 'college',
          minWidth: 200,
          align: 'center',
          sortable: true
        }
      ];
      let arr01 = this.restTableCellWidth(arr1);
      this.tableColumns = arr01.concat(this.tableColumns);
    }
    this.getCollegeList();
    this.getSchoolList();
    this.getZyList();
    this.getRecordPage();
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.onRestWindow);
  }

};
</script>
<style scoped lang="less">
.cbox {
  padding: 0 10px;
  box-sizing: border-box;
}

.h-7 {
  height: 7%;
}


.ch50 {
  height: 50px;
}

.ctable {
  // /deep/.ivu-table-body {
  //     height: 74%;
  // }
  @media (max-width: 1920px) {
    /deep/ .ivu-table-body {
      height: 78% !important;
    }
  }

  @media (min-width: 1921px) and (max-width: 3440px) {
    /deep/ .ivu-table-body {
      height: 74.5% !important;
    }
  }
}

</style>